﻿using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using TidyBlog.Entity;
using TidyBlog.BLL;
using TidyBlog.Data;
using TidyBlog.MVC;
using TidyBlog.MVC.WWW.Models;

namespace TidyBlog.MVC.WWW.Controllers
{
    /// <summary>
    /// 文章控制器 /Article/{action}
    /// </summary>
    [FrontActionFilter]
    public class ArticleController : FrontController
    {
        /// <summary>
        /// 匹配HTML字符串
        /// </summary>
        protected static readonly Regex HtmlStrings = new Regex(@"<.*?>|&.*?;", RegexOptions.Compiled);


        /// <summary>
        /// 获取边栏公共数据
        /// </summary>
        /// <param name="model">页面模型</param>
        protected void GetSidebarData(ArticleBase model)
        {
            // 获取当前分类查看数排行
            model.ArticleViewRank = ArticleBLL.GetTopView(ViewBag.CurrentPosition.CategoryId);
            // 获取推荐文章
            model.RecommendArticles = ArticleBLL.GetRecommends();
        }

        /// <summary>
        /// 文章列表页
        /// </summary>
        /// <param name="id">分类编号</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ActionResult Index(int? id, int? page)
        {
            var categoryId = id.GetValueOrDefault();
            var model = new ArticleIndex();

            Category currentPosition = null;
            if (categoryId > 0)
            {
                currentPosition = CategoryBLL.Read(categoryId);
                if (currentPosition == null)
                {
                    throw new Exception("分类不存在");
                }
                if (currentPosition.Weight == 0)
                {
                    throw new Exception("此分类已被隐藏");
                }

                ViewBag.Title = currentPosition.CategoryName + " | " + ViewBag.Title;

                if (!String.IsNullOrEmpty(currentPosition.Description))
                {
                    ViewBag.Description = currentPosition.Description;
                }
                if (!String.IsNullOrEmpty(currentPosition.Keywords))
                {
                    ViewBag.Keywords = currentPosition.Keywords;
                }
            }
            else
            {
                currentPosition = Category.Home;
            }

            ViewBag.CurrentPosition = currentPosition;

            // 读取文章数据
            var articleData = ArticleBLL.ListByCategory(categoryId, page.HasValue ? page.Value : 1);
            model.ArticlePaginator = new Paginator(
                articleData.CurrentPage,
                articleData.PageCount,
                Url.Action("Index", new { id = categoryId }) + "/{0}"
            );
            model.ArticleData = articleData;

            GetSidebarData(model);

            return View(model);
        }

        /// <summary>
        /// 文章详细页
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        public ActionResult Detail(int? id)
        {
            var model = new ArticleDetail();

            var article = ArticleBLL.Read(id.GetValueOrDefault());
            if (article == null || article.Weight == 0)
            {
                throw new Exception("文章不存在或已被隐藏");
            }

            ViewBag.CurrentPosition = new Category()
            {
                CategoryId = article.CategoryId,
                CategoryName = article.CategoryName
            };

            model.CurrentArticle = article;

            // 上一篇
            model.PrevArticle = ArticleBLL.GetPreviousOf(article);
            // 下一篇
            model.NextArticle = ArticleBLL.GetNextOf(article);

            if (!String.IsNullOrEmpty(article.Summary))
            {
                // 把摘要中的HTML删除后作为描述
                ViewBag.Description = HtmlStrings.Replace(article.Summary, String.Empty);
            }
            if (!String.IsNullOrEmpty(article.Keywords))
            {
                ViewBag.Keywords = article.Keywords;
            }

            ViewBag.Title = article.Title + " | " + article.CategoryName + " | " + ViewBag.Title;

            GetSidebarData(model);

            return View(model);
        }

        /// <summary>
        /// 增加文章查看数
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        public ActionResult View(int? id)
        {
            Response.ContentType = "text/plain";
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(1));

            if (id.HasValue)
            {
                ArticleBLL.AddViewCount(id.Value);
            }

            return new EmptyResult();
        }

        /// <summary>
        /// 文章RSS
        /// </summary>
        /// <returns></returns>
        public ActionResult RSS()
        {
            Response.ContentType = "text/xml";

            DataPaging<Article> result = ArticleBLL.ListByCategory(0, 1);

            return View(result != null && result.Data != null ? result.Data : null);
        }
    }
}